package com.guoxin.part4.chapter17;

import java.util.stream.IntStream;

/**
 * @author guoxin
 * @date 2019/8/31
 */
public class ReadWriteLockTest {
    private final static String TEXT = "Thisistheexampleforreadwritelock";

    public static void main(String[] args) {
        final ShareData shareData = new ShareData(50);

        //创建两个线程进行写数据
        IntStream.range(0, 2).mapToObj(value -> new Thread(() -> {
            for (int index = 0; index < TEXT.length(); index++) {
                try {
                    char c = TEXT.charAt(index);
                    shareData.write(c);
                    System.out.println(Thread.currentThread() + " write " + c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        })).forEach(Thread::start);

        //创建10个线程进行读数据
        IntStream.range(0, 10).mapToObj(value -> new Thread(() -> {
            while (true) {
                try {
                    System.out.println(Thread.currentThread() + " read " +
                            new String(shareData.read()));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        })).forEach(Thread::start);
    }
}
